#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
快速测试东财接口是否可用
可用于验证接口本身是否正常，还是在特定网络环境下不可用
"""
import requests
import json
import sys
from datetime import datetime


def test_eastmoney_api(url, params, description="接口"):
    """测试东财API接口"""
    print(f"\n{'='*60}")
    print(f"测试: {description}")
    print(f"URL: {url}")
    print(f"{'='*60}")
    
    # 测试1: 基本连接测试
    print("\n1. 基本连接测试（无参数）...")
    try:
        r = requests.get(url, timeout=10)
        print(f"   ✅ 状态码: {r.status_code}")
        print(f"   ✅ 响应长度: {len(r.content)} 字节")
    except requests.exceptions.ConnectionError as e:
        print(f"   ❌ 连接错误: {e}")
        return False
    except requests.exceptions.Timeout as e:
        print(f"   ❌ 超时: {e}")
        return False
    except Exception as e:
        print(f"   ❌ 错误: {type(e).__name__}: {e}")
    
    # 测试2: 带完整参数测试
    print("\n2. 完整参数测试...")
    try:
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
            "Referer": "http://quote.eastmoney.com/",
        }
        r = requests.get(url, params=params, headers=headers, timeout=10)
        print(f"   ✅ 状态码: {r.status_code}")
        print(f"   ✅ 响应长度: {len(r.content)} 字节")
        
        # 尝试解析JSON
        try:
            data = r.json()
            if "data" in data:
                print(f"   ✅ JSON解析成功")
                if "diff" in data["data"]:
                    count = len(data["data"]["diff"])
                    print(f"   ✅ 数据条数: {count}")
                    if count > 0:
                        print(f"   ✅ 第一条数据示例: {list(data['data']['diff'][0].keys())[:5]}")
                    return True
                else:
                    print(f"   ⚠️  响应中没有 'diff' 字段")
                    print(f"   响应结构: {list(data.keys())}")
            else:
                print(f"   ⚠️  响应中没有 'data' 字段")
                print(f"   响应结构: {list(data.keys())}")
        except json.JSONDecodeError as e:
            print(f"   ❌ JSON解析失败: {e}")
            print(f"   响应前100字符: {r.text[:100]}")
            return False
            
    except requests.exceptions.ConnectionError as e:
        print(f"   ❌ 连接错误: {e}")
        return False
    except requests.exceptions.Timeout as e:
        print(f"   ❌ 超时: {e}")
        return False
    except Exception as e:
        print(f"   ❌ 错误: {type(e).__name__}: {e}")
        return False
    
    return False


def main():
    print("="*60)
    print("东财接口可用性测试")
    print(f"测试时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print("="*60)
    
    # 测试1: 股票实时行情接口
    stock_url = "http://82.push2.eastmoney.com/api/qt/clist/get"
    stock_params = {
        "pn": "1",
        "pz": "50",
        "po": "1",
        "np": "1",
        "ut": "bd1d9ddb04089700cf9c27f6f7426281",
        "fltt": "2",
        "invt": "2",
        "fid": "f12",
        "fs": "m:0 t:6,m:0 t:80,m:1 t:2,m:1 t:23,m:0 t:81 s:2048",
        "fields": "f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f14,f15,f16,f17,f18,f20,f21,f22,f23,f24,f25,f26,f37,f38,f39,f40,f41,f45,f46,f48,f49,f57,f61,f100,f112,f113,f114,f115,f221",
        "_": "1623833739532",
    }
    stock_ok = test_eastmoney_api(stock_url, stock_params, "股票实时行情接口")
    
    # 测试2: ETF实时行情接口
    etf_url = "http://88.push2.eastmoney.com/api/qt/clist/get"
    etf_params = {
        "pn": "1",
        "pz": "50",
        "po": "1",
        "np": "1",
        "ut": "bd1d9ddb04089700cf9c27f6f7426281",
        "fltt": "2",
        "invt": "2",
        "wbp2u": "|0|0|0|web",
        "fid": "f12",
        "fs": "b:MK0021,b:MK0022,b:MK0023,b:MK0024",
        "fields": "f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f12,f13,f14,f15,f16,f17,f18,f20,f21,f23,f24,f25,f22,f11,f62,f128,f136,f115,f152",
        "_": "1672806290972",
    }
    etf_ok = test_eastmoney_api(etf_url, etf_params, "ETF实时行情接口")
    
    # 总结
    print("\n" + "="*60)
    print("测试总结")
    print("="*60)
    print(f"股票接口: {'✅ 可用' if stock_ok else '❌ 不可用'}")
    print(f"ETF接口: {'✅ 可用' if etf_ok else '❌ 不可用'}")
    
    if not stock_ok and not etf_ok:
        print("\n💡 提示:")
        print("   - 如果本地测试失败，可能是接口本身的问题")
        print("   - 如果本地测试成功但服务器测试失败，说明是网络环境限制")
        print("   - 建议在不同网络环境（本地、服务器、容器）分别测试")
    
    return 0 if (stock_ok and etf_ok) else 1


if __name__ == "__main__":
    sys.exit(main())

